package com.zhangmeng.tools.controller;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-03-16 11:22
 */
@Slf4j
public class SocketServerController {

    @FXML
    public TextField server_status;

    @FXML
    public Button stop;

    @FXML
    public Button start;

    @FXML
    public TextField port;

    public static ObservableList<String> message_list = FXCollections.observableArrayList();

    @FXML
    public TextArea message_show;

    private WebSocketServer webSocketServer;

    private boolean isStart;

    public static Map<String,WebSocket> map = new HashMap<>();

    @FXML
    public void initialize() {
        if (server_status.getText().length() == 0 ){
            server_status.setText("服务未启动!");
        }

        port.setText(String.valueOf(9999));
        start.setOnAction(event -> {
            if (isStart){
                try {
                    webSocketServer.stop();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            sshServer_init();
        });

        stop.setOnAction(event -> {
            if (isStart){
                try {
                    webSocketServer.stop();
                    isStart = false;
                    server_status.setText("服务已经停止!端口:" + port.getText());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        message_list.addListener((ListChangeListener<String>) c -> {
            while (c.next()) {
                if (c.wasAdded()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (String s : message_list) {
                        stringBuilder.append(s);
                    }
                    receive(stringBuilder.toString());
                }
            }
        });
    }

    public void sshServer_init(){
        //启动socket server
        webSocketServer = new WebSocketServer(new InetSocketAddress(Integer.parseInt(port.getText()))) {

            @Override
            public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
                add_message("WebSocketServer:open----------------------------------------------");
                put(webSocket);
            }

            @Override
            public void onClose(WebSocket webSocket, int i, String s, boolean b) {
                add_message("WebSocketServer:onClose--------------------------------------------");
                remove(webSocket);
            }

            @Override
            public void onMessage(WebSocket webSocket, String s) {
                add_message("WebSocketServer:onMessage--------------------------------------------");
                add_message(s);
                webSocket.send(s);
            }

            @Override
            public void onError(WebSocket webSocket, Exception e) {
                add_message("WebSocketServer:onError--------------------------------------------");
            }

            @Override
            public void onStart() {
                add_message("WebSocketServer:onStart--------------------------------------------");
            }
        };
        webSocketServer.start();
        isStart = true;
        server_status.setText("服务已启动!端口:" + port.getText());
    }

    public void put(WebSocket webSocket){
        String resourceDescriptor = webSocket.getResourceDescriptor();
        String[] split = resourceDescriptor.split("\\?");
        if (split.length > 0){
            String params = split[1];
            String userId = params.split("&")[0].split("=")[1];
            map.put(userId,webSocket);
        }
    }

    public WebSocket get(String userId){
        return map.get(userId);
    }

    public void remove(WebSocket webSocket){
        String resourceDescriptor = webSocket.getResourceDescriptor();
        String[] split = resourceDescriptor.split("\\?");
        if (split.length > 0){
            String params = split[1];
            String userId = params.split("&")[0].split("=")[1];
            map.remove(userId);
        }
    }

    public  void receive(String msg) {
        Platform.runLater(() -> {
            this.message_show.setText(msg);
        });
    }

    public static void add_message(String msg){
        message_list.add(msg);
        message_list.add(System.lineSeparator());
    }
}
